package cn.itcast.bos.service.base.impl;

import java.util.Date;
import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.base.AreaRepository;
import cn.itcast.bos.dao.base.FixedAreaRepository;
import cn.itcast.bos.dao.take_delivery.OrderRepository;
import cn.itcast.bos.dao.take_delivery.WorkBillRepository;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.constants.Constants;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.service.base.OrderService;
@Service
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderRepository orderRepository;
	
	//注入定区Dao层
	@Autowired
	private FixedAreaRepository fixedAreaRepository;
	
	//注入区域
	@Autowired
	private AreaRepository areaRepository;
	
	//注入工单
	@Autowired
	private WorkBillRepository WorkBillRepository;
	
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	
	@Override
	public void saveOrder(Order order) {
		System.out.println(order+"=====================传递到serviceImpl心中的order===================");
		//订单号 随机生成
		order.setOrderNum(UUID.randomUUID().toString());
		//订单生成日期
		order.setOrderTime(new Date());
		order.setStatus("1");//待取件
		
		//设置持久态的 寄件人省市区
		Area sendArea = order.getSendArea();
		Area persistSendArea = areaRepository.findByProvinceAndCityAndDistrict(
				sendArea.getProvince(), sendArea.getCity(), sendArea.getDistrict());
		
		//设置持久态的 收件人省市区
		Area recArea = order.getSendArea();
		Area persistrecArea = areaRepository.findByProvinceAndCityAndDistrict(
				sendArea.getProvince(), sendArea.getCity(), sendArea.getDistrict());
		
		order.setSendArea(persistSendArea);
		order.setRecArea(persistrecArea);
		
		
		//自动分单，基于CRM完全地址匹配，获取定区，匹配快递员
		String fixedAreaId = WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/customer/findFixedAreaIdByAddress?address="+order.getSendAddress())
		.accept(MediaType.APPLICATION_JSON).get(String.class);
		if(fixedAreaId!=null){
			//根据定区Id获取定区
			FixedArea fixedArea = fixedAreaRepository.findOne(fixedAreaId);
			Courier courier = fixedArea.getCouriers().iterator().next();
			if(courier!=null){
				//证明快递员存在
				System.out.println("自动分单===========");
				saveOrder(order, courier);
				
				//生成工单  发送短信
				generateWorkBill(order);
				return;
			}
			
		}
		
		//自动分单逻辑    基于省市区  查询关键字  匹配地址  基于分区实现自动分单
		for ( SubArea subArea : persistSendArea.getSubareas()) {
			//查询用户下单的省市区信息中是否包括关键字  辅助关键字
			if(order.getSendAddress().contains(subArea.getKeyWords())||order.getSendAddress().contains(subArea.getAssistKeyWords())){
				//根据分区找到定区  然后找到快递员
				Courier courier = subArea.getFixedArea().getCouriers().iterator().next();  // 找到众多快递员中的一个
				if(courier!=null){
					//证明快递员存在
					System.out.println("自动分单===========");
					saveOrder(order, courier);
					
					//生成工单 发送短信
					generateWorkBill(order);
					return;
				}
	
			}
		}
		//以上都不符合   进入人工分单
		order.setOrderType("2");
		orderRepository.save(order);
	}

	//保存订单
	private void saveOrder(Order order, Courier courier) {
		order.setOrderType("1");
		
		//快递员关联订单
		order.setCourier(courier);
		//保存订单
		orderRepository.save(order);
	}
	
	//生成工单 发送短信
	public void generateWorkBill(final Order order){
		WorkBill workBill = new WorkBill();
		workBill.setType("新"); //新单:没有确认货物状态的
		workBill.setPickstate("新单");//取单状态
		workBill.setBuildtime(new Date());
		workBill.setRemark(order.getRemark());  //备注
		final String smsNumber = RandomStringUtils.randomNumeric(4);
		workBill.setSmsNumber(smsNumber);  //短信序号
		workBill.setOrder(order);
		workBill.setCourier(order.getCourier());
		
		//保存工单
		WorkBillRepository.save(workBill);
		
		// 发送短信
		// 调用MQ服务，发送一条消息
		jmsTemplate.send("bos_sms",new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", order.getCourier().getTelephone());
				mapMessage.setString("msg",
						"短信序号：" + smsNumber + ",取件地址：" + order.getSendAddress()
							+ ",联系人:" + order.getSendName() + ",手机:"
							+ order.getSendMobile() + "，快递员捎话："
							+ order.getSendMobileMsg());
				return mapMessage;
			}
		
		});
		
		workBill.setPickstate("已通知");//修改工单状态
	}

	@Override
	public Order findByOrderNum(String orderNum) {
		
		return orderRepository.findByOrderNum(orderNum);
	}
	
}
